/*
 * MainFrame.java
 *
 *  created: 9.9.2011
 *  charset: UTF-8
 *  license: MIT (X11) (See LICENSE file for full license)
 */
package cz.mp.k3bg.gui;

import cz.mp.k3bg.Application;
import cz.mp.k3bg.Images;
import cz.mp.k3bg.Preferences;
import cz.mp.k3bg.BookState;
import cz.mp.k3bg.core.BookFiles;
import cz.mp.k3bg.core.Metadata;
import cz.mp.k3bg.log.LoggerManager;
import cz.mp.util.StringUtils;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import static cz.mp.k3bg.TextSource.*;
import static cz.mp.k3bg.Application.*;

/**
 * Hlavní okno programu.
 * 
 * @author Martin Pokorný
 * @version 0.1
 * @see MainFrameMenu
 * @see MainFrameTabbedPane
 * @see TabPanel
 */
public class MainFrame extends JFrame {

    private static final boolean DEBUG = false;
    private static final Logger logger =
            LoggerManager.getLogger(MainFrame.class, DEBUG);

    public static final int MINIMAL_WIDTH = 700;

    public static final int DEFAULT_WIDTH = 750;
    public static final int DEFAULT_HEIGHT = 550;
    
    private static MainFrame instance = null;

    private MainFrameMenu mainMenu = new MainFrameMenu();

    private MainFrameTabbedPane mainTabbePanel = new MainFrameTabbedPane();

    private MetadataPanel metadataPanel = new MetadataPanel();
    private BookFilesPanel filesPanel = new BookFilesPanel();
    private KindlegenPanel kindlegenPanel = new KindlegenPanel();

    // -----

    /** */
    private MainFrame() {
        super(Application.NAME);
                    
        try {
            initComponents();
            initEventHandlers();
            initFrame();
        } catch (Exception ex) {
            logger.severe(ex.toString());
            if (DEBUG) {  ex.printStackTrace();  }            
            Dialogs.showErrorDialog(ex);
        }
    }

    /**
     * 
     * @return 
     */
    public static MainFrame getInstance() {
        if (instance == null) {
            logger.finer("new!");
            instance = new MainFrame();
        }
        return instance;
    }
    
    /**
     * 
     */
    private void initComponents() {
        logger.finer("");
        
        mainTabbePanel.addTab(metadataPanel);
        mainTabbePanel.addTab(filesPanel);
        mainTabbePanel.addTab(kindlegenPanel);
        
        mainTabbePanel.setSelectedComponent(metadataPanel);

        this.getContentPane().add(mainTabbePanel);

        this.setJMenuBar(mainMenu);
    }
    
    /** */
    private void initFrame() {
        logger.finer("");
        
        ArrayList<Image> icons = new ArrayList<Image>();
        icons.add(Images.getImage(Images.LOGO_16).getImage());
        icons.add(Images.getImage(Images.LOGO_32).getImage());
        icons.add(Images.getImage(Images.LOGO_48).getImage());
        icons.add(Images.getImage(Images.LOGO_128).getImage());
        this.setIconImages(icons);

        this.pack();
        this.setMinimumSize(
                new Dimension(
                        Math.min(MINIMAL_WIDTH, this.getWidth()), 
                        this.getHeight()));
        this.setSize(Math.max(MINIMAL_WIDTH, this.getWidth()), this.getHeight());

        Preferences.useStoredBounds(this);

        logger.config("size = " + this.getWidth() + " x " + this.getHeight());
    }

    /** */
    private void initEventHandlers() {
        this.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                logger.finer("");
                
                exit(0);
            }
        });

        mainTabbePanel.addChangeListener(new ChangeListener() {
            private TabPanel lastSelectedTab = metadataPanel;

            @Override
            public void stateChanged(ChangeEvent evt) {
                logger.fine("(mainTabbePanel) selected_idx = " + 
                        mainTabbePanel.getSelectedIndex());

                Component selected = mainTabbePanel.getSelectedComponent();
                if (! (selected instanceof TabPanel)) {
                    return;
                }
                TabPanel selectedTab = (TabPanel) selected;

                // změna z  MetadataPanel  na cokoliv jiného
                if (lastSelectedTab instanceof MetadataPanel
                        && ! (selectedTab instanceof MetadataPanel)) {
                    Metadata metadata = metadataPanel.createMetadata();
                    if (metadata != null) {
                        logger.info(" MetadataPanel --> * ");
                    }
                    BookState.getMainInstance().setMetadata(metadata);
                }
                
                // změna z  BookFilesPanel  na cokoliv jiného
                if (lastSelectedTab instanceof BookFilesPanel
                        && ! (selectedTab instanceof BookFilesPanel)) {
                    BookFiles bookFiles = filesPanel.createBookFiles();
                    if (bookFiles != null) {
                        logger.info(" BookFilesPanel --> * ");
                    }
                    BookState.getMainInstance().setBookFiles(bookFiles);
                }

                lastSelectedTab = selectedTab;

                selectedTab.update();
            }
        });
    }

    @Override
    public void setVisible(boolean b) {
        super.setVisible(b);

        if (b == true) {
            instance.newVersionDialog();
        }
    }

    /**
     * 
     */
    private void newVersionDialog() {        
        String message = getLocText("gui.new_version_popup.message");
        if (Preferences.isVersionChange(this.getClass(), VERSION_NUMBER) &&
                !StringUtils.isEmpty(message) &&
                !message.equals("gui.new_version_popup.message")) {

            JOptionPane.showMessageDialog(this, 
                    getLocText("gui.new_version_popup.message"),
                    getLocText("gui.new_version_popup.title", VERSION_NUMBER),
                    JOptionPane.INFORMATION_MESSAGE);
            
            Preferences.putLastRunVersion(this.getClass(), VERSION_NUMBER);
        }
    }
    
    /**
     * Ukončení programu se zadaným návratovým kódem.
     * 
     * @param returnCode 
     */
    public void exit(int returnCode) {
        logger.info("returnCode = " + returnCode);
        
        Preferences.putWindowArea(this, this.getBounds());

        System.exit(returnCode);        
    } 
    
    /**
     * 
     */
    public void clearAllPanels() {
        BookState.getMainInstance().clear();
        metadataPanel.clear();
        filesPanel.clear();
        kindlegenPanel.clear();
    }

}   // MainFrame.java

